<template>
  <BasicModal
    v-bind="$attrs"
    :width="600"
    :title="'新增分类'"
    :help-message="'add category'"
    @register="register"
    @ok="handleOk"
  >
    <div class="mb-5">
      <a-alert
        message="如果需要在一级、二级分类下添加子分类请选择父级分类，添加一级分类则不用选择"
        type="info"
        show-icon
      />
    </div>
    <a-form
      ref="formRef"
      :model="state.formState"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <a-form-item label="参数名称" name="cat_name">
        <a-input v-model:value="state.formState.cat_name" placeholder="请输入参数名称" />
      </a-form-item>
      <a-form-item label="一级分类" name="firstLevel">
        <a-select
          allowClear
          v-model:value="state.formState.firstLevel"
          placeholder="请选择一级分类"
          @change="handleLevelChange"
          :disabled="props.editStatus"
        >
          <a-select-option
            v-for="item in shopGoodsStore.secondLevel"
            :key="item.value"
            :value="item.value"
            >{{ item.label }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="二级分类" name="secondLevel">
        <a-select
          allowClear
          v-model:value="state.formState.secondLevel"
          placeholder="请选择二级分类"
          :disabled="state.secondLabelDisabled || props.editStatus"
        >
          <a-select-option v-for="item in secondList" :key="item.value" :value="item.value">{{
            item.label
          }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue';
  import { computed, reactive, ref, toRaw, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useShopGoodsStore } from '/@/store/modules/shopGoodsStore';

  type stateModel = {
    formState: {
      cat_name: string;
      firstLevel: number | null;
      secondLevel: number | null;
    };
    secondLabelDisabled: boolean;
  };

  const props = defineProps({
    editStatus: Boolean,
    editRow: Object,
  });

  const emits = defineEmits(['addResult', 'editResult']);

  const shopGoodsStore = useShopGoodsStore();

  const [register, { closeModal, setModalProps, getVisible }] = useModalInner();

  const rules = {
    cat_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  };

  const formRef = ref();

  const state: stateModel = reactive({
    formState: {
      cat_name: '',
      firstLevel: null,
      secondLevel: null,
    },
    secondLabelDisabled: true,
  });

  const secondList = computed(() => {
    const toRawSecondLevel = toRaw(shopGoodsStore.secondLevel);
    const filterLevel = toRawSecondLevel.filter(
      (item: any) => item.value == state.formState.firstLevel,
    );
    return filterLevel.length ? filterLevel[0].children : [];
  });

  const handleLevelChange = (value: number) => {
    if (!value) {
      state.formState.secondLevel = null;
      state.secondLabelDisabled = true;
      return;
    }
    state.secondLabelDisabled = false;
  };

  const addCategoryData = async () => {
    const { cat_name, firstLevel, secondLevel } = state.formState;
    const params = {
      cat_name,
      cat_pid: 0,
      cat_level: 0,
    };
    if (firstLevel) {
      params.cat_pid = firstLevel;
      params.cat_level = 1;
    }
    if (secondLevel) {
      params.cat_pid = secondLevel;
      params.cat_level = 2;
    }
    const data = await shopGoodsStore.addCategory({ ...params });
    emits('addResult', data);
    message.success('添加成功');
  };

  const editCategoryData = async () => {
    try {
      const cat_id = props.editRow?.cat_id;
      const { cat_name } = state.formState;
      const data = await shopGoodsStore.updateCategory({ id: cat_id, cat_name });
      emits('editResult', data);
      message.success('修改成功');
    } catch (error) {
      console.error(error);
    }
  };

  const handleOk = () => {
    formRef.value
      .validate()
      .then(async () => {
        if (props.editStatus) {
          editCategoryData();
        } else {
          addCategoryData();
        }
        closeModal();
      })
      .catch((error: any) => {
        console.error(error);
      });
  };

  watch(
    () => getVisible?.value,
    (visible) => {
      if (!visible) {
        state.formState.cat_name = '';
        formRef.value.resetFields();
        state.secondLabelDisabled = true;
      }
    },
  );

  watch(
    () => props.editStatus,
    (editStatus) => {
      if (editStatus) {
        const cat_name = props.editRow?.cat_name;
        const firstLevel = props.editRow?.firstLevel;
        const secondLevel = props.editRow?.secondLevel;
        state.formState = {
          cat_name,
          firstLevel,
          secondLevel,
        };
        setModalProps({
          title: '修改分类',
          helpMessage: 'edit category',
        });
      } else {
        setModalProps({
          title: '新增分类',
          helpMessage: 'add category',
        });
      }
    },
  );
</script>
